package javaweb.oa;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import javaweb.oa.Utils.DBUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = null;
        String password = null;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("username")){
                    username = cookie.getValue();
                }else if(cookie.getName().equals("password")){
                    password = cookie.getValue();
                }
            }
        }
        if(username!=null&&password!=null){
            // 验证用户名和密码是否正确
            // 正确表示登录成功，错误表示登录失败
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            boolean flag = false;
            try{
                conn = DBUtil.getConnection();
                String sql = "select * from user where username=? and password=?";
                ps = conn.prepareStatement(sql);
                ps.setString(1,username);
                ps.setString(2,password);
                rs = ps.executeQuery();
                if(rs.next()){
                    flag = true;
                }

            }catch(SQLException e){
                e.getClass().getName();
            }finally{
                DBUtil.close(conn,ps,rs);
            }
            if(flag){
                HttpSession session = request.getSession();
                session.setAttribute("username",username);
                response.sendRedirect(request.getContextPath()+"/dept/list");
            }else{
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }
        }else{
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }

    }
}
